<template>
  <div class="report-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1>举报管理</h1>
      <p class="subtitle">查看和处理用户举报信息</p>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="filter-card">
      <div class="filter-section">
        <div class="search-bar">
          <el-input
            v-model="searchQuery"
            placeholder="搜索举报原因"
            style="width: 300px"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        
        <div class="filter-controls">
          <el-select v-model="statusFilter" placeholder="状态筛选" style="width: 120px" @change="handleFilter">
            <el-option label="全部" value="" />
            <el-option label="待处理" value="PENDING" />
            <el-option label="已处理" value="RESOLVED" />
            <el-option label="已驳回" value="REJECTED" />
          </el-select>
          
          <el-select v-model="typeFilter" placeholder="举报类型" style="width: 140px" @change="handleFilter">
            <el-option label="全部类型" value="" />
            <el-option label="用户" value="USER" />
            <el-option label="帖子" value="POST" />
            <el-option label="评论" value="COMMENT" />
            <el-option label="资源" value="RESOURCE" />
          </el-select>
          
          <el-button type="primary" @click="refreshData">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 举报列表 -->
    <el-card class="table-card">
      <el-table
        :data="reports"
        v-loading="loading"
        stripe
        style="width: 100%"
        :default-sort="{ prop: 'createTime', order: 'descending' }"
      >
        <el-table-column prop="id" label="举报ID" width="100" sortable />
        
        <el-table-column prop="reporterId" label="举报人" width="100" />
        
        <el-table-column prop="targetType" label="举报类型" width="100">
          <template #default="scope">
            <el-tag :type="getTypeTagType(scope.row.targetType)" size="small">
              {{ getTypeText(scope.row.targetType) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="targetId" label="被举报对象ID" width="120" />
        
        <el-table-column prop="reason" label="举报原因" min-width="200" show-overflow-tooltip>
          <template #default="scope">
            <div class="reason-text" @click="viewReportDetail(scope.row)">
              {{ scope.row.reason }}
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 'PENDING'" type="warning" size="small">待处理</el-tag>
            <el-tag v-else-if="scope.row.status === 'RESOLVED'" type="success" size="small">已处理</el-tag>
            <el-tag v-else type="info" size="small">已驳回</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="举报时间" width="160" sortable>
          <template #default="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="handleTime" label="处理时间" width="160" sortable>
          <template #default="scope">
            {{ scope.row.handleTime ? formatTime(scope.row.handleTime) : '-' }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="viewReportDetail(scope.row)"
            >
              查看详情
            </el-button>
            
            <el-button
              v-if="scope.row.status === 'PENDING'"
              type="success"
              size="small"
              @click="handleReport(scope.row)"
            >
              处理
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 举报详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="举报详情" width="700px" top="5vh">
      <div v-if="selectedReport" class="report-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="举报ID">{{ selectedReport.id }}</el-descriptions-item>
          <el-descriptions-item label="举报人ID">{{ selectedReport.reporterId }}</el-descriptions-item>
          <el-descriptions-item label="被举报类型">
            <el-tag :type="getTypeTagType(selectedReport.targetType)">
              {{ getTypeText(selectedReport.targetType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="被举报对象ID">{{ selectedReport.targetId }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag v-if="selectedReport.status === 'PENDING'" type="warning">待处理</el-tag>
            <el-tag v-else-if="selectedReport.status === 'RESOLVED'" type="success">已处理</el-tag>
            <el-tag v-else type="info">已驳回</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="举报时间">{{ formatTime(selectedReport.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="处理时间" :span="2">
            {{ selectedReport.handleTime ? formatTime(selectedReport.handleTime) : '未处理' }}
          </el-descriptions-item>
          <el-descriptions-item label="举报原因" :span="2">
            <div class="reason-content">{{ selectedReport.reason }}</div>
          </el-descriptions-item>
          <el-descriptions-item v-if="selectedReport.handleResult" label="处理结果" :span="2">
            <div class="handle-result">{{ selectedReport.handleResult }}</div>
          </el-descriptions-item>
        </el-descriptions>
        
        <div v-if="selectedReport.status === 'PENDING'" class="report-actions">
          <el-button type="success" @click="showHandleDialog('RESOLVED')">
            标记为已处理
          </el-button>
          <el-button type="warning" @click="showHandleDialog('REJECTED')">
            驳回举报
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 处理举报对话框 -->
    <el-dialog v-model="handleDialogVisible" title="处理举报" width="500px">
      <el-form :model="handleForm" label-width="100px">
        <el-form-item label="处理状态">
          <el-tag v-if="handleForm.status === 'RESOLVED'" type="success">已处理</el-tag>
          <el-tag v-else type="warning">已驳回</el-tag>
        </el-form-item>
        <el-form-item label="处理结果" required>
          <el-input
            v-model="handleForm.handleResult"
            type="textarea"
            :rows="4"
            placeholder="请输入处理结果说明"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmHandle">确认处理</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getReportsPage, handleReport as apiHandleReport } from '@/api/report'

// 数据定义
const reports = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 搜索和筛选
const searchQuery = ref('')
const statusFilter = ref('')
const typeFilter = ref('')

// 对话框
const detailDialogVisible = ref(false)
const handleDialogVisible = ref(false)
const selectedReport = ref(null)

// 处理表单
const handleForm = ref({
  id: null,
  status: '',
  handleResult: '',
  handlerId: 1 // TODO: 从用户登录信息获取
})

// 获取举报列表
const fetchReports = async () => {
  loading.value = true
  try {
    const params: any = {
      page: currentPage.value,
      size: pageSize.value,
      status: statusFilter.value || undefined,
      targetType: typeFilter.value || undefined
    }
    const res = await getReportsPage(params)
    if (res && res.code === 200 && res.data) {
      reports.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      reports.value = []
      total.value = 0
      ElMessage.error(res?.message || '获取举报列表失败')
    }
  } catch (error) {
    reports.value = []
    total.value = 0
    ElMessage.error('获取举报列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  // 这里只做本地过滤示例，实际可在后端支持模糊搜索时传递 reason 参数
  fetchReports()
}

// 筛选
const handleFilter = () => {
  fetchReports()
}

// 刷新数据
const refreshData = () => {
  fetchReports()
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  fetchReports()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchReports()
}

// 查看举报详情
const viewReportDetail = (report: any) => {
  selectedReport.value = report
  detailDialogVisible.value = true
}

// 处理举报
const handleReport = (report: any) => {
  selectedReport.value = report
  showHandleDialog('RESOLVED')
}

// 显示处理对话框
const showHandleDialog = (status: string) => {
  handleForm.value = {
    id: selectedReport.value.id,
    status: status,
    handleResult: '',
    handlerId: 997 // TODO: 从用户登录信息获取
  }
  handleDialogVisible.value = true
}

// 确认处理
const confirmHandle = async () => {
  if (!handleForm.value.handleResult.trim()) {
    ElMessage.warning('请输入处理结果说明')
    return
  }
  try {
    const res = await apiHandleReport({
      id: handleForm.value.id,
      handlerId: handleForm.value.handlerId || 997,
      status: handleForm.value.status,
      handleResult: handleForm.value.handleResult
    })
    if (res && (res.code === 0 || res.code === 200)) {
      ElMessage.success('举报处理成功')
      handleDialogVisible.value = false
      detailDialogVisible.value = false
      fetchReports()
    } else {
      ElMessage.error(res?.message || '处理失败，请重试')
    }
  } catch (error) {
    ElMessage.error('处理失败，请重试')
  }
}

// 获取类型标签类型
const getTypeTagType = (type: string) => {
  const typeMap = {
    USER: 'primary',
    POST: 'success',
    COMMENT: 'warning',
    RESOURCE: 'info'
  }
  return typeMap[type] || ''
}

// 获取类型文本
const getTypeText = (type: string) => {
  const typeMap = {
    USER: '用户',
    POST: '帖子',
    COMMENT: '评论',
    RESOURCE: '资源'
  }
  return typeMap[type] || '未知'
}

// 格式化时间
const formatTime = (time: string) => {
  if (!time) return '未知'
  return new Date(time).toLocaleString()
}

onMounted(() => {
  fetchReports()
})
</script>

<style scoped>
.report-management {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  color: #2c3e50;
  font-size: 2rem;
  margin-bottom: 8px;
  font-weight: 600;
}

.subtitle {
  color: #7f8c8d;
  font-size: 1rem;
  margin: 0;
}

.filter-card {
  margin-bottom: 24px;
  border-radius: 12px;
}

.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.filter-controls {
  display: flex;
  gap: 12px;
  align-items: center;
}

.table-card {
  border-radius: 12px;
  overflow: hidden;
}

.reason-text {
  color: #409eff;
  cursor: pointer;
  font-weight: 500;
  max-width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.reason-text:hover {
  text-decoration: underline;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

.report-detail {
  padding: 16px 0;
}

.reason-content, .handle-result {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 12px;
  border: 1px solid #e9ecef;
  line-height: 1.6;
}

.report-actions {
  margin-top: 24px;
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  gap: 12px;
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-descriptions-item__label) {
  font-weight: 600;
}
</style>
